package com.zz.bsea.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;
import org.springframework.stereotype.Component;
@Component
public class MessageUtil {
	
	
	/**
	 * 获得ACCESS_TOKEN
	* @Title: getAccess_token
	* @Description: 获得ACCESS_TOKEN
	* @param @return 设定文件
	* @return String 返回类型
	* @throws
	 */
	private static String getAccess_token(){ 
	 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WeiChatConfig.appid + "&secret=" +WeiChatConfig.secretid;
	 String accessToken = null;
	 try {
	 URL urlGet = new URL(url);
	 HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); 

	 http.setRequestMethod("GET"); //必须是get方式请求 
	 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
	 http.setDoOutput(true); 
	 http.setDoInput(true);
	 System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
	 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
	 http.connect();

	 InputStream is =http.getInputStream();
	 int size =is.available();
	 byte[] jsonBytes =new byte[size];
	 is.read(jsonBytes);
	 String message=new String(jsonBytes,"UTF-8");

	 JSONObject demoJson = new JSONObject(message);
	 accessToken = demoJson.getString("access_token");

	 System.out.println(message);
	 is.close();
	 } catch (Exception e) {
	 e.printStackTrace();
	 }
	 return accessToken;
	 }
	
	
	/**
	 * @throws UnsupportedEncodingException 
	 * 创建Menu
	* @Title: createMenu
	* @Description: 创建Menu
	* @param @return
	* @param @throws IOException 设定文件
	* @return int 返回类型
	* @throws
	 */
	 public static String getImag() throws UnsupportedEncodingException {
	
		 
	 String access_token= getAccess_token();
	 System.out.println("access_token=="+access_token);
	 String action = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id=H97YFB7HLazqz5UZT1lnGcGeO8AsoWA8yAC2LHeQBbQ-RzyvzoMmDey6tcnles9c";
	 try {
	 URL url = new URL(action);
	 HttpURLConnection http = (HttpURLConnection) url.openConnection(); 

	 http.setRequestMethod("GET"); 
	 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
	 http.setDoOutput(true); 
	 http.setDoInput(true);
	 System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
	 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
	 http.connect();

	 InputStream is =http.getInputStream();
	 BufferedInputStream bis=new BufferedInputStream(is);
	 int size =is.available();
	 byte[] jsonBytes =new byte[size];
	 is.read(jsonBytes);
	 File f=new File("C:\\tmp\\2.jpg");
	//OutputStream是一个抽象类
	//FileOutputStream是OutputStream的子类
	OutputStream out=new FileOutputStream(f);
	int intstart=0;
	byte[] buffer=new byte[8192];
	while((intstart=is.read(buffer,0,8192))!=-1){
	out.write(buffer,0,intstart);
	}
	out.close();
	is.close();
	//BufferedOutputStream bout=new BufferedOutputStream(out);
	//out.write(jsonBytes);
	//out.close();
	 String message=new String(jsonBytes,"UTF-8");
	 } catch (MalformedURLException e) {
	 e.printStackTrace();
	 } catch (IOException e) {
	 e.printStackTrace();
	 } 
	 return "ok";
	 }
	 
	 
	 /**
	  * 根据文件id下载文件
	  * 
	  * @param mediaId
	  *  媒体id
	  * @throws Exception
	  */
	 public InputStream getInputStream(String mediaId) {
	// GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();
	 String accessToken = getAccess_token();
	 InputStream is = null;
	 String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
	  + accessToken + "&media_id=" + mediaId;
	 try {
	  URL urlGet = new URL(url);
	  HttpURLConnection http = (HttpURLConnection) urlGet
	   .openConnection();
	  http.setRequestMethod("GET"); // 必须是get方式请求
	  http.setRequestProperty("Content-Type",
	   "application/x-www-form-urlencoded");
	  http.setDoOutput(true);
	  http.setDoInput(true);
	  System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
	  System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
	  http.connect();
	  // 获取文件转化为byte流
	  is = http.getInputStream();
	 } catch (Exception e) {
	  e.printStackTrace();
	 }
	 return is;
	 }

	 /**
	  * 获取下载图片信息（jpg）
	  * 
	  * @param mediaId
	  *  文件的id
	  * @throws Exception
	  */
	 public boolean  saveImageToDisk(String mediaId,String path) throws Exception {
		 boolean flag=false;
	 InputStream inputStream = getInputStream(mediaId);
	 byte[] data = new byte[1024];
	 int len = 0;
	 FileOutputStream fileOutputStream = null;
	 try {
	  fileOutputStream = new FileOutputStream(path);
	  while ((len = inputStream.read(data)) != -1) {
	  fileOutputStream.write(data, 0, len);
	  }
	 } catch (IOException e) {
	  e.printStackTrace();
	 } finally {
		 flag=true;
	  if (inputStream != null) {
	  try {
	   inputStream.close();
	  } catch (IOException e) {
	   e.printStackTrace();
	  }
	  }
	  if (fileOutputStream != null) {
	  try {
	   fileOutputStream.close();
	  } catch (IOException e) {
	   e.printStackTrace();
	  }
	  }
	 }
	 return flag;
	 }

	public static void main(String[] args) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
//		MessageUtil mu=new MessageUtil();
//		try {
//			mu.saveImageToDisk("SHMNWZZduQ4Mxx9CytQapKUx365ByO0yKRr6V22j37P5NOipynP4KGtvh5xjKZyc");
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//System.out.println(getImag());
	}

}
